import React, { useState, useRef, useEffect } from 'react';
import styles from './VipVR.module.css';
import xl from '../Lyf/img/xl.jpg'
import Hua from './Hua'

const VipVR = () => {
  const vipLevels = [
    {
      level: 1,
      name: '青铜会员',
      points: 0,
      needed: 600,
      cardColor: 'linear-gradient(135deg, #CD7F32 0%, #B87333 50%, #8B5A2B 100%)', // 青铜渐变
      badgeColor: '#B87333',
      textColor: '#FFF8DC',
      startColor: '#e09b46'
    },
    {
      level: 2,
      name: '白银会员',
      points: 600,
      needed: 600,
      cardColor: 'linear-gradient(135deg, #E6E6E6 0%, #C0C0C0 50%, #A8A8A8 100%)', // 白银渐变
      badgeColor: '#C0C0C0',
      textColor: '#333333',
      startColor: '#9e9e9d'
    },
    {
      level: 3,
      name: '黄金会员',
      points: 1200,
      needed: 1100,
      cardColor: 'linear-gradient(135deg, #FFD700 0%, #D4AF37 50%, #DAA520 100%)', // 黄金渐变
      badgeColor: '#e8bc38',
      textColor: 'white',
      startColor: '#f9d423'
    },
    {
      level: 4,
      name: '铂金会员',
      points: 2300,
      needed: 1700,
      cardColor: 'linear-gradient(135deg, #F5F5F5 0%, #E5E4E2 50%, #D3D3D3 100%)', // 铂金渐变
      badgeColor: '#CECECE',
      textColor: 'white',
      startColor: '#e0e0e0'
    },
    {
      level: 5,
      name: '钻石会员',
      points: 4000,
      needed: 4000,
      cardColor: 'linear-gradient(135deg, #E6E0E9 0%, #D8BFD8 50%, #C8A2C8 100%)', // 钻石渐变
      badgeColor: '#C8A2C8',
      textColor: 'white',
      startColor: '#e0b4e0'
    },
    {
      level: 6,
      name: '至尊会员',
      points: 8000,
      needed: 0,
      cardColor: 'linear-gradient(135deg, #bead3f 0%, #3d381d 50%, #121112 100%)', // 黑金渐变
      badgeColor: 'black',
      textColor: '#FFD700',
      startColor: '#e09b46'
    }
  ];
  // 1. 初始化状态和ref
  const [currentMember, setCurrentMember] = useState(() => {
    const savedMember = localStorage.getItem('currentMember');
    return savedMember ? JSON.parse(savedMember) : null;
  });

  const [startX, setStartX] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const containerRef = useRef(null);
  const cardRefs = useRef([]);
  const [arcRotation, setArcRotation] = useState(0);

  // const [currentLevel, setCurrentLevel] = useState(1); // 初始化为1级

  const [currentLevel, setCurrentLevel] = useState(() => {
    const savedMember = localStorage.getItem('currentMember');
    if (savedMember) {
      const member = JSON.parse(savedMember);
      const totalAmount = member.totalAmount || 0;
      // 从最高级开始检查，找到第一个符合条件的等级
      for (let i = vipLevels.length - 1; i >= 0; i--) {
        if (totalAmount >= vipLevels[i].points) {
          return vipLevels[i].level;
        }
      }
    }
    return 1; // 默认1级
  });

  // 自动同步卡片索引
  const [currentIndex, setCurrentIndex] = useState(currentLevel - 1);
  useEffect(() => {
    setCurrentIndex(currentLevel - 1);
  }, [currentLevel]);

  // 2. VIP等级配置
  // 在VIP等级配置中修改背景渐变


  // 3. 计算当前等级和进度
  const calculateProgress = () => {
    if (!currentMember) return { progress: 0 };

    const totalAmount = currentMember.totalAmount || 0;
    let progress = 0;
    const nextLevel = vipLevels.find(level => level.level === currentLevel + 1);

    if (nextLevel) {
      progress = ((totalAmount - vipLevels[currentLevel - 1].points) / nextLevel.needed) * 100;
    } else {
      progress = 100; // 最高等级
    }

    return { progress };
  };

  const { progress } = calculateProgress();
  // const [currentIndex, setCurrentIndex] = useState(currentLevel - 1);

  // 4. 监听本地存储变化
  useEffect(() => {
    const handleStorageChange = (e) => {
      if (e.key === 'currentMember') {
        const member = e.newValue ? JSON.parse(e.newValue) : null;
        setCurrentMember(member);

        // 更新当前等级
        if (member) {
          const totalAmount = member.totalAmount || 0;
          for (let i = vipLevels.length - 1; i >= 0; i--) {
            if (totalAmount >= vipLevels[i].points) {
              setCurrentLevel(vipLevels[i].level);
              break;
            }
          }
        }
      }
    };
    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  // 自动居中当前卡片
  useEffect(() => {
    if (cardRefs.current[currentIndex]) {
      cardRefs.current[currentIndex].scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'center'
      });
    }
  }, [currentIndex]);


  // 6. 触摸和鼠标事件处理
  const handleTouchStart = (e) => {
    setStartX(e.touches[0].clientX);
    setIsDragging(true);
  };

  const handleTouchMove = (e) => {
    if (!isDragging) return;
    const currentX = e.touches[0].clientX;
    const diff = startX - currentX;

    if (diff > 50 && currentIndex < vipLevels.length - 1) {
      handleCardSwipe(currentIndex + 1);
      setIsDragging(false);
    } else if (diff < -50 && currentIndex > 0) {
      handleCardSwipe(currentIndex - 1);
      setIsDragging(false);
    }
  };

  const handleTouchEnd = () => {
    setIsDragging(false);
  };

  const handleMouseDown = (e) => {
    setStartX(e.clientX);
    setIsDragging(true);
  };

  const handleMouseMove = (e) => {
    if (!isDragging) return;
    const currentX = e.clientX;
    const diff = startX - currentX;

    if (diff > 50 && currentIndex < vipLevels.length - 1) {
      setCurrentIndex(currentIndex + 1);
      setIsDragging(false);
    } else if (diff < -50 && currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
      setIsDragging(false);
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  const lightenColor = (color, percent = 20) => {
    /* 实现颜色变亮逻辑 */
    return color;
  }

  const darkenColor = (color, percent = 20) => {
    /* 实现颜色变暗逻辑 */
    return color;
  }


  // 新增半圆滑块的计算逻辑
  // 处理等级变化
  const handleLevelChange = (level) => {
    setCurrentLevel(level);
    setCurrentIndex(level - 1); // 同步更新卡片索引
  };

  // 滑动卡片处理
  const handleCardSwipe = (newIndex) => {
    setCurrentIndex(newIndex);
    setCurrentLevel(newIndex + 1);
  };



  // 修改点击处理
  const handleCardClick = (index) => {
    handleCardSwipe(index);
  };


  return (
    <div className={styles.container}>
      {/* 半圆滑块 */}
      <div className={styles.bigbox}>
        <div className={styles.arcSliderContainer}>
          <Hua
            currentLevel={currentLevel}
            onLevelChange={(level) => {
              setCurrentLevel(level);
              setCurrentIndex(level - 1);
            }}
          />
        </div>

        {/* 会员等级卡 */}
        <div
          className={styles.sliderContainer}
          ref={containerRef}
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={handleMouseUp}
        >
          <div className={styles.sliderTrack}>
            {vipLevels.map((vip, index) => {
              // 计算当前卡片是否达到或超过该等级
              const isAchieved = currentMember ?.totalAmount >= vip.points;
              // 是否是当前实际等级
              const isCurrentLevel = currentLevel === vip.level;
              // 是否是已解锁但非当前等级
              const isUnlockedButNotCurrent = isAchieved && !isCurrentLevel;

              return (
                <div
                  key={vip.level}
                  ref={el => cardRefs.current[index] = el}
                  className={`${styles.memberCard} 
                  ${index === currentIndex ? styles.active : ''}
                  ${isAchieved ? styles.achieved : ''}
                  ${isCurrentLevel ? styles.currentLevel : ''}`}
                  onClick={() => setCurrentIndex(index)}
                  style={{
                    transform: `scale(${index === currentIndex ? 1 : 0.9})`,
                    opacity: index === currentIndex ? 1 : isAchieved ? 0.85 : 0.7,
                    transition: 'all 0.3s ease',
                    background: vip.cardColor,
                    color: vip.textColor
                  }}
                >
                  <div className={styles.leftSection}>
                    <div className={styles.memberLevel}>
                      {vip.name} Lv.{vip.level}

                    </div>
                    <div className={styles.currentPoints}>
                      当前充值：¥{currentMember ?.totalAmount || 0}
                    </div>
                    <div className={styles.upgradeInfo}>
                      <span>
                        {(() => {
                          // 当前等级配置
                          const currentVip = vipLevels[currentIndex];
                          // 下一级配置（可能不存在）
                          const nextVip = vipLevels[currentIndex + 1];

                          if (currentVip.level === 6) {
                            return '已达最高等级';
                          }

                          if (!nextVip) {
                            return '已达最高等级';
                          }

                          const totalAmount = currentMember ?.totalAmount || 0;
                          // 计算升级所需金额
                          const needAmount = nextVip.points - totalAmount;

                          if (needAmount <= 0) {
                            return '等级已满';
                          }

                          return `还差¥${needAmount}可升级为${nextVip.name}`;
                        })()}
                      </span>
                      <div className={styles.progressBar} style={{ backgroundColor: 'rgb(219, 217, 217)' }}>
                        <div
                          className={styles.progressFill}
                          style={{
                            width: `${isCurrentLevel ? progress : isAchieved ? 100 : 0}%`,
                            background: isCurrentLevel ?
                              'linear-gradient(to right, #FFD700, #FFA500)' : // 改为金色到橙色的渐变
                              'linear-gradient(to right, #FFD700, #FFA500)',
                            transition: 'width 0.5s ease, background 0.5s ease' // 添加平滑过渡
                          }}
                        ></div>
                      </div>
                    </div>
                  </div>
                  <div className={styles.rightSection}>
                    <div className={styles.vBadge}>
                      <div
                        className={styles.vLetter}
                        style={{
                          color: vip.textColor,
                          textShadow: `2px 2px 4px rgba(0, 0, 0, 0.5), 0 0 10px ${vip.badgeColor}`,
                        }}
                      >V{vip.level}</div>
                      <div
                        className={styles.vRing}
                        style={{
                          background: `linear-gradient(135deg, 
                          ${lightenColor(vip.badgeColor, 30)} 0%, 
                          ${vip.badgeColor} 50%, 
                          ${darkenColor(vip.badgeColor, 20)} 100%)`,
                          boxShadow: `
                          0 0 15px ${vip.badgeColor},
                          inset 0 0 10px rgba(255, 255, 255, 0.3)`,
                        }}
                      ></div>
                      <div
                        className={styles.vShine}
                        style={{
                          background: `linear-gradient(90deg, 
                          rgba(255,255,255,0) 0%, 
                          rgba(255,255,255,0.3) 50%, 
                          rgba(255,255,255,0) 100%)`,
                        }}
                      ></div>
                      <div
                        className={styles.vStar}
                        style={{
                          background: `linear-gradient(135deg, 
                          ${lightenColor(vip.startColor, 20)} 0%, 
                          ${vip.startColor} 50%, 
                          ${darkenColor(vip.startColor, 20)} 100%)`,
                          filter: `drop-shadow(0 0 5px ${vip.startColor})`
                        }}
                      ></div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div className={styles.fixedShoppingArea}>
        <div className={styles.vipShoppingArea}>
          <div className={styles.vipShoppingHeader}>
            <h2>会员专享</h2>
          </div>

          <div className={styles.productGrid}>
            {/* 左侧商品 */}
            <div className={styles.productCard}>
              <div >
                <img src={xl} alt="" className={styles.productImagePlaceholder} />
              </div>
              <h3 className={styles.productTitle}>周大福铂金素链</h3>
              <div className={styles.priceInfo}>
                <span className={styles.originalPrice}>价值￥1980</span>
                <span className={styles.discountPrice}>会员价￥599</span>
              </div>

              {/* <span className={styles.vipTag}>铂金专享</span> */}
            </div>

            {/* 右侧商品 */}
            <div className={styles.productCard}>
              <div>
                <img src={xl} alt="" className={styles.productImagePlaceholder} />
              </div>
              <h3 className={styles.productTitle}>周大福心形O字链铂金手链</h3>
              <div className={styles.priceInfo}>
                <span className={styles.originalPrice}>价值￥2880</span>
                <span className={styles.discountPrice}>会员价￥599</span>
              </div>

              {/* <span className={styles.vipTag}>铂金专享</span> */}
            </div>

            <div className={styles.productCard}>
              <div>
                <img src={xl} alt="铂金戒指" className={styles.productImagePlaceholder} />
              </div>
              <h3 className={styles.productTitle}>周大福铂金简约戒指</h3>
              <div className={styles.priceInfo}>
                <span className={styles.originalPrice}>价值￥2280</span>
                <span className={styles.discountPrice}>会员价￥799</span>
              </div>
            </div>

            {/* 新增商品6 - 铂金手镯 */}
            <div className={styles.productCard}>
              <div>
                <img src={xl} alt="铂金手镯" className={styles.productImagePlaceholder} />
              </div>
              <h3 className={styles.productTitle}>周大福铂金简约手镯</h3>
              <div className={styles.priceInfo}>
                <span className={styles.originalPrice}>价值￥3280</span>
                <span className={styles.discountPrice}>会员价￥999</span>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  );
};

export default VipVR;